import SessionUserUtil from '../../../data/session/sessionUser'
import SessionUtil, { JxbHttpClient } from '../../../data/session/session'
var App = getApp();
var ApiUrl = App.data.ApiUrl;
var Common = require('../../../utils/common.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isBomb: false,
    if_success: false,
    is_for: false,
    id: 4,
    redpacket: {},
    SMCTime: 60,
    SMCTimes: true,
    SMCode_Lock: false,
    SMCode_Msg: '获取验证码',
    SMCode: '',
    if_no: false,
    isLogin: false,
    btnText: '立即领取'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '优惠券免费领取',
    });
    if (options.id) {
      this.setData({
        id: options.id
      })
    }
    if (options.scene) {
      var scene = decodeURIComponent(options.scene)
      this.setData({
        id: scene.id
      })
    }
    let page = this
    this.couponRedPacket().then(()=>{
      Common.when_user_change_clear_the_storage(function () {
        if (SessionUserUtil.getInstanceSync().userId <= 0) {
          page.setData({
            if_token: true,
            btnText: '微信登录并领取'
          })
        } else {
          page.setData({
            if_token: false,
            btnText: '立即领取'
          })
        }
      })
    })
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
  },
  /**
  * 更新验证码
  */
  updateSMCode: function (e) {
    this.setData({
      SMCode: e.detail.value
    })
  },
  /**
   * 提交后弹出
   */
  isBombs: function () {
    var page = this;
    if (page.data.redpacket.is_can_receive) {
      this.setData({
        isBomb: !page.data.isBomb
      })
    }
  },
  /**
  *  更新手机号
  */
  updatephone: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },
  /**
   * 获取信息
   */
  couponRedPacket() {
    return (new JxbHttpClient()).request({
      url: '/AppMaster/Public/couponRedPacket',
      data: {
        id: this.data.id
      }
    }).then(jxbResp => {
        let data = jxbResp.data
        data.couponDetail.coupon_amount = parseInt(data.couponDetail.coupon_amount)
        data.couponDetail.limit_amount = parseInt(data.couponDetail.limit_amount)
        data.couponDetail.start_time = this.timestampToTime(data.couponDetail.start_time)
        data.couponDetail.end_time = this.timestampToTime(data.couponDetail.end_time)
        this.setData({
          redpacket: data
        })
        if (!data.is_can_receive) {
          this.setData({
            isBomb: true,
            if_success: false,
            is_for: false,
            if_no: true,
            message: data.receive_msg
          })
        }
        return jxbResp
      }).catch(error => {
      wx.showToast({
        title: error.message,
        duration: 2000,
        icon: 'none',
        complete: ()=>{
          setTimeout(()=>{
            wx.switchTab({
              url: '/pages/index/index'
            })
          }, 2000)
        }
      });
    })
  },
  /**
   * 领取
   */
  receive: function () {
    var page = this;
    var phone = page.data.phone;
    phone = phone ? phone : '';
    Common.my_request({
      url: '/AppMaster/Public/getCouponRedPacket',
      data: {
        id: page.data.id,
        phone: phone,
        name: ''
      },
      success: function (res) {
        if (res.data.result == 0) {
          page.setData({
            isBomb: true,
            if_success: true,
            is_for: true,
          })
          page.changeConsulant()
        } else {
          if (res.data.data) {
            if (res.data.data.status == 110) {
              page.setData({
                isBomb: true,
                if_success: false,
                is_for: false,
              })
              return false;
            }
          }
          page.setData({
            if_no: true,
            message: res.data.message,
            isBomb: true,
          })
        }
      }
    })
  },
  // 切换顾问
  changeConsulant: function () {
    var page = this;
    //couponDetail
    Common.my_request({
      url: 'AppMaster/Account/selectNewConsultant',
      data: {
        salesman_id: page.data.redpacket.salesman_id
      },
      success: function (res) {
        if (res.data.result == 0) {
          wx.showToast({
            title: '顾问切换成功',
            duration: 2000
          })
          Common.when_user_change_clear_the_storage();

        }
      }
    });
  },
  /**
   * 时间戳转时间YYYY-MM-DD hh:mm:ss
   */
  timestampToTime: function (timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
  },
  /**
   * 优惠券点击跳转到对应产品
   * coupon_type:"2",allow_item_id:"32" 跳到商品详情
   * coupon_type:"1",allow_item_id:"32|64" 跳到商品列表,allow_item_id:"32" 跳到商品详情
   * info:优惠券类型_商品id
   */
  goDetail: function (e) {
    var dtype = this.data.redpacket.couponDetail.coupon_type;//coupon_type
    var id = this.data.redpacket.couponDetail.allow_item_id;//allow_item_id
    if (dtype == 1) {
      var intid = parseInt(id);
      /**如果当前的可用商品只有一个 && intid存在 */
      if (intid == id && intid) {
        wx.navigateTo({
          url: '/pages/product/detail/detail?itemId=' + id
        })
      } else {
        wx.switchTab({
          url: '/pages/product/index/index'
        })
      }
    } else {
      wx.navigateTo({
        url: '/pages/product/detail/detail?itemId=' + id
      })

    }
  },
  /**
   * 去首页
   */
  toIndex() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  /**
   * 验证码获取
   */
  getSMCode: function (e) {
    var page = this;
    var phones = page.data.phone;
    page.setData({
      SMCode_Lock: true
    });
    if (page.data.SMCTime < 60 && page.data.SMCTime > 0) {
      return false;
    }
    // 获取验证码
    wx.request({
      url: ApiUrl + '/AppMaster/Login/bindPhoneSendMessageCode',
      data: {
        phone: phones,
      },
      header: {
        'content-type': 'json'
      },
      success: function (res) {
        if (res.data.result == 0) {
          wx.showToast({
            title: '验证码已发送',
            icon: 'success',
            duration: 2000
          })
          // 倒计时显示
          page.SMCode_Msg();
        } else {
          page.setData({
            SMCTime: 60,
            SMCode_Lock: false,
            SMCode_Msg: '获取验证码'
          })
          console.log(res.data.message)
          Common.Alert('错误提示', res.data.message);
        }

      }
    })

  },
  /**
   * 倒计时
   */
  SMCode_Msg: function () {
    console.log('SMCode_Msg');
    var page = this;
    var SMCTimers;
    var SMCTime = page.data.SMCTime;
    var SMCode_Msg = page.data.SMCode_Msg;
    var SMCode_Lock = page.data.SMCode_Lock;
    if (SMCTime > 1) {
      SMCTime--;
      SMCode_Msg = '重新获取(' + SMCTime + ')';
      page.setData({
        SMCTime: SMCTime,
        SMCode_Msg: SMCode_Msg,
        SMCTimes: false,
      })
      // 定时器执行
      SMCTimers = setTimeout(function () {
        page.SMCode_Msg();
      }, 1000);

    } else {
      clearTimeout(SMCTimers);
      page.setData({
        SMCTime: 60,
        SMCode_Lock: false,
        SMCode_Msg: '获取验证码',
        SMCTimes: true,
      })
    }
  },
  /**
    * 确定运行
   */
  onLogin_SMC: function () {
    var page = this;
    console.log(page.data)
    SessionUserUtil.getInstance().then(user => {
      if(user.userId > 0){
        this.receive()
      }else{
        wx.navigateTo({
          url: `/pages/my/logintype/logintype?couponId=${page.data.id}`,
        })
      }
    })
  },
  wechatLogin() {
    wx.navigateTo({
      url: '',
    })
  },
  vipLogin() {
    wx.navigateTo({
      url: '',
    })
  }
})